from hashlib import new
import threading
from gui import GUI
import copy


class Env:
    def __init__(self, maze) -> None:
        self.maze = maze
        self.backup = copy.deepcopy(self.maze)
        self.size = len(maze)

        self.gui = GUI(maze)
        self.gui.renderMaze()

        self.lock = threading.Lock()

    def crossBorder(self, pos, direct) -> bool:
        x, y = pos
        if direct == 0 and x == 0 or direct == 1 and x == self.size-1 or \
                direct == 2 and y == 0 or direct == 3 and y == self.size-1:
            return True
        return False

    def reachable(self, pos) -> bool:
        '''
            判断位置pos是否在maze矩阵之外
            TODO:这个函数会被多个agent调用, 需要加锁保数据一致性
        '''
        x, y = pos
        # 边界
        if x < 0 or x > self.size-1 or y < 0 or y > self.size-1:
            return False

        # 这个是判断下一步是否可到达
        self.lock.acquire()
        if self.maze[x][y] == 1 or self.maze[x][y] == 2:
            self.lock.release()
            return False
        self.lock.release()
        return True

    def updatePos(self, old_pos, new_pos) -> None:
        '''
            更新矩阵
            需要加锁保数据一致性
        '''
        self.lock.acquire()
        x, y = old_pos
        self.maze[x][y] = 0
        nx, ny = new_pos
        self.maze[nx][ny] = 2
        self.gui.changeColor(old_pos, new_pos)
        self.lock.release()

    def mainloop(self) -> None:
        self.gui.mainloop()

    def reset(self) -> None:
        self.maze = copy.deepcopy(self.backup)
        self.gui.reset()
